package com.shangdiao.sd_server.c_client.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shangdiao.sd_server.constant.Constant;
import com.shangdiao.sd_server.constant.ErrorCode;
import com.shangdiao.sd_server.constant.TableConstant;
import com.shangdiao.sd_server.generator.pojo.SdCompany;
import com.shangdiao.sd_server.generator.pojo.SdCompanyBase;
import com.shangdiao.sd_server.generator.pojo.SdCompanyBaseExample;
import com.shangdiao.sd_server.generator.pojo.SdCompanyPhoto;
import com.shangdiao.sd_server.generator.pojo.SdCompanyPhotoExample;
import com.shangdiao.sd_server.generator.pojo.SdInternship;
import com.shangdiao.sd_server.generator.pojo.SdInternshipExample;
import com.shangdiao.sd_server.generator.pojo.SdPInternshipExample;
import com.shangdiao.sd_server.pojo.ResponseMsg;
import com.shangdiao.sd_server.pojo.Row;
import com.shangdiao.sd_server.service.CompanyService;
import com.shangdiao.sd_server.service.DicService;
import com.shangdiao.sd_server.service.PostService;
import com.shangdiao.sd_server.service.RedisService;
import com.shangdiao.sd_server.service.SequenceService;
import com.shangdiao.sd_server.util.CommonUtil;
import com.shangdiao.sd_server.util.MD5Util;
import com.shangdiao.sd_server.util.MsgUtil;
import com.shangdiao.sd_server.util.RequestUtil;
import com.shangdiao.sd_server.util.StringUtil;

@Controller
@RequestMapping("/open/c_reg")
public class CompanyLoginController {
	
	@Autowired
	DicService dicService;
	@Autowired
	CompanyService companyService;
	@Autowired
	RedisService redisService;
	@Autowired
	SequenceService sequenceService;
	@Autowired
	PostService postService;
	
	@RequestMapping(value = { "/checkTel.json" })
	@ResponseBody
	public Object checktel(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		String tel = RequestUtil.get(request, "tel");
		if(StringUtil.isBlank(tel)){
			return new ResponseMsg("缺少必要参数", ErrorCode.ERROR, null);
		}
		if(!StringUtil.isMobile(tel)){
			return new ResponseMsg("手机号格式错误", ErrorCode.ERROR, null);
		}
		SdCompanyBaseExample example = new SdCompanyBaseExample();
		example.or().andTelEqualTo(tel).andDelEqualTo(Constant.DEL_NO);
		int count = companyService.countCompanyBaseByExample(example);
		
		if(count > 0){
			retMsg = new ResponseMsg("此手机号已注册",ErrorCode.ERROR, null);
		}else{
			String auth_code = CommonUtil.genAuth_code();
			redisService.set(Constant.COMPANY_TOKEN_PRE + tel, auth_code, 60 * 10);
			String content = "您的企业注册验证码为：" + auth_code;
			MsgUtil.sendMsg(tel, content);
			retMsg = new ResponseMsg("",ErrorCode.OK, null);
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/checkAuthCode.json" })
	@ResponseBody
	@Transactional
	public Object checkAuthCode(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		String tel = RequestUtil.get(request, "tel");
		String auth_code = RequestUtil.get(request, "auth_code");
		if(StringUtil.isBlank(tel) || StringUtil.isBlank(auth_code)){
			retMsg = new ResponseMsg("缺少必要参数", ErrorCode.ERROR, null);
		}else{
			if(!auth_code.equals(redisService.get(Constant.COMPANY_TOKEN_PRE + tel))){
				retMsg = new ResponseMsg("验证码错误", ErrorCode.ERROR, null);
			}else{
				redisService.del(Constant.COMPANY_TOKEN_PRE + tel);//验证成功后即删除
				retMsg = new ResponseMsg("验证成功", ErrorCode.OK, null);
			}
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/register.json" })
	@ResponseBody
	@Transactional
	public Object register(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		try{
			String tel = RequestUtil.get(request, "tel");
			String pwd = RequestUtil.get(request, "pwd");
			String companyName = RequestUtil.get(request, "companyName");
			String email = RequestUtil.get(request, "email");
			Integer dicFieldId = RequestUtil.getInt(request, "dicFieldId");
			String dicField = RequestUtil.get(request, "dicField");
			String logo = RequestUtil.get(request, "logo");
			if(StringUtil.isBlank(tel) || StringUtil.isBlank(pwd)){
				return new ResponseMsg("缺少必要参数", ErrorCode.ERROR, null);
			}
			SdCompanyBaseExample example = new SdCompanyBaseExample();
			example.or().andTelEqualTo(tel).andDelEqualTo(Constant.DEL_NO);
			int count = companyService.countCompanyBaseByExample(example);
			
			if(count > 0){//
				return new ResponseMsg("此手机号已注册",ErrorCode.ERROR, null);
			}
			if(!StringUtil.isBlank(email) && !StringUtil.isEmail(email)){
				return new ResponseMsg("邮箱格式错误", ErrorCode.ERROR, null);
			}
			boolean logoFlag = true;
			if(!StringUtil.isBlank(logo)){
				logo = logo.substring(logo.lastIndexOf("/") + 1, logo.length());
				logoFlag = CommonUtil.Move(Constant.TEMP_FILE_PATH + logo, Constant.LOGO_FILE_PATH + logo);
			}
			if(logoFlag){
				Integer companyId = sequenceService.nextSequence(TableConstant.SD_COMPANY);
				SdCompanyBase companyBase = new SdCompanyBase();
				companyBase.setCompanyId(companyId);
				companyBase.setCompanyName(companyName);
				companyBase.setTel(tel);
				companyBase.setEmail(email);
				companyBase.setPwd(MD5Util.encodeByMD5(pwd));
				companyBase.setDicFieldId(dicFieldId);
				companyBase.setDicFieldName(dicField);
				Date create_date = new Date();
				companyBase.setCreateDate(create_date);
				companyService.insertCompanyBase(companyBase);
				SdCompany company = new SdCompany();
				company.setCompanyId(companyId);
				company.setCompanyName(companyName);
				company.setTel(tel);
				company.setEmail(email);
				company.setDicFieldId(dicFieldId);
				company.setDicFieldName(dicField);
				if(!StringUtil.isBlank(logo)){
					company.setLogo(Constant.LOGO_FILE_URL + logo);
				}
				company.setCreateDate(create_date);
				companyService.insertCompany(company);
				Row result = afterLogin(companyId);
				retMsg = new ResponseMsg("注册成功", ErrorCode.OK, result);
			}else{
				retMsg = new ResponseMsg("移动图片失败", ErrorCode.ERROR, null);
			}
		}catch(Exception e){
			e.printStackTrace();
			retMsg = new ResponseMsg("注册失败", ErrorCode.SERVER_ERROR, null);
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/login.json" })
	@ResponseBody
	@Transactional
	public Object login(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		try{
			String tel = RequestUtil.get(request, "tel");
			String pwd = RequestUtil.get(request, "pwd");
			if(StringUtil.isBlank(tel) || StringUtil.isBlank(pwd)){
				return new ResponseMsg("缺少必要参数", ErrorCode.ERROR, null);
			}
			SdCompanyBaseExample example = new SdCompanyBaseExample();
			example.or().andTelEqualTo(tel)
				.andDelEqualTo(Constant.DEL_NO);
			List<SdCompanyBase> companyBaselist = companyService.selectCompanyBaseByExample(example);
			if(companyBaselist.size() == 0){
				retMsg = new ResponseMsg("该账号不存在", ErrorCode.ERROR, null);
			}else{
				SdCompanyBase companyBase = companyBaselist.get(0);
				String pwd_out = MD5Util.encodeByMD5(pwd);
				String pwd_in = companyBase.getPwd();
				if(pwd_out.equals(pwd_in)){
					Integer companyId = companyBase.getCompanyId();
					Row result = afterLogin(companyId);
					retMsg = new ResponseMsg("登录成功", ErrorCode.OK, result);
				}else{
					retMsg = new ResponseMsg("密码错误", ErrorCode.ERROR, null);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			retMsg = new ResponseMsg("登录失败", ErrorCode.SERVER_ERROR, null);
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/findPwd.json" })
	@ResponseBody
	@Transactional
	public ResponseMsg findPwd(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		String tel = RequestUtil.get(request, "tel");
		if(StringUtil.isBlank(tel)){
			return new ResponseMsg("缺少必要参数！", ErrorCode.ERROR, null);
		}
		SdCompanyBaseExample example = new SdCompanyBaseExample();
		example.or().andTelEqualTo(tel).andDelEqualTo(Constant.DEL_NO);
		List<SdCompanyBase> companyBaseList = companyService.selectCompanyBaseByExample(example);
		if(companyBaseList != null && companyBaseList.size() > 0){
			SdCompanyBase companyBase = companyBaseList.get(0);
			String randomPwd = CommonUtil.genRandomPwd(6);
			companyBase.setPwd(MD5Util.encodeByMD5(randomPwd));
			companyService.updateCompanyBaseById(companyBase);
			String content = "您的企业账号登录密码已临时重置为：" + randomPwd + "，请尽快登录并重新修改密码，以保障账号安全！";
			MsgUtil.sendMsg(tel, content);
			retMsg = new ResponseMsg("",ErrorCode.OK, null);
		}else{
			retMsg = new ResponseMsg("此手机号不存在！",ErrorCode.ERROR, null);
		}
		return retMsg;
	}
	
	public Row afterLogin(Integer companyId){
		String token = MD5Util.encodeByMD5(Constant.COMPANY_TOKEN_PRE + companyId + System.currentTimeMillis());
		redisService.set(Constant.COMPANY_TOKEN_PRE + companyId, token,  60 * 60 * 24 * 30);
		Row result = new Row();
		result.put("identityFlag", "c");//身份标识
		result.put("uid", companyId);
		result.put("token", token);
		//企业信息
		SdCompany company = companyService.selectCompanyById(companyId);
		result.put("companyName", company.getCompanyName());//公司名称
		result.put("dicFieldId", company.getDicFieldId());//
		result.put("dicFieldName", company.getDicFieldName());//
		result.put("website", company.getWebsite());//
		result.put("districtId", company.getDistrictId());//
		result.put("district", company.getDistrict());//
		result.put("location", company.getLocation());//
		result.put("email", company.getEmail());//
		result.put("tel", company.getTel());//
		result.put("intro", company.getIntro());//
		result.put("logo", Constant.DOMAIN + company.getLogo());//
		//未读消息数
		SdInternshipExample intExample = new SdInternshipExample();
		intExample.or().andCompanyIdEqualTo(companyId)
		.andStatusEqualTo(Constant.STATUS_ON)
		.andDelEqualTo(Constant.DEL_NO);
		List<SdInternship> intList = postService.selectInternshipList(intExample);
		int count = 0;
		if(intList.size() != 0){
			List<Integer> internshipIdList = new ArrayList<Integer>();
			for(SdInternship internship : intList){
				internshipIdList.add(internship.getInternshipId());
			}
			SdPInternshipExample pIntExample = new SdPInternshipExample();
			pIntExample.or().andInternshipIdIn(internshipIdList)
				.andSourceEqualTo(Constant.STATUS_ON)//个人
				.andStatusEqualTo(Constant.STATUS_ON);//未读
			count = postService.countPInternship(pIntExample);
		}
		result.put("unreadCount", count);
		//企业头图
		SdCompanyPhotoExample photoExample = new SdCompanyPhotoExample();
		photoExample.or().andCompanyIdEqualTo(companyId)
			.andDelEqualTo(Constant.DEL_NO);
		List<SdCompanyPhoto> companyPhotoList = companyService.selectCompanyPhoto(photoExample);
		List<String> photoList = new ArrayList<String>();
		for(SdCompanyPhoto companyPhoto : companyPhotoList){
			photoList.add(Constant.DOMAIN + companyPhoto.getCompanyPhotoUrl());
		}
		result.put("photoList", photoList);//
		return result;
	}
	
	public static void main(String[] args) {
		
	}
	
}
